from rest_framework import serializers
from .models import AITemplate, RequirementAnalysis, AIGenerationLog, GeneratedTestCaseMapping
from projects.models import Project, Version
from cases.models import TestCase

class AITemplateSerializer(serializers.ModelSerializer):
    """AI提示词模板序列化器"""
    class Meta:
        model = AITemplate
        fields = ['id', 'name', 'content', 'project_type', 'description', 'created_at', 'updated_at', 'is_default']

class AITemplateCreateSerializer(serializers.ModelSerializer):
    """AI提示词模板创建序列化器"""
    class Meta:
        model = AITemplate
        fields = ['name', 'content', 'project_type', 'description', 'is_default']

class RequirementAnalysisSerializer(serializers.ModelSerializer):
    """需求分析序列化器"""
    # 添加项目和版本信息
    project_name = serializers.ReadOnlyField(source='project.name')
    version_name = serializers.ReadOnlyField(source='version.version_number', allow_null=True)
    
    class Meta:
        model = RequirementAnalysis
        fields = ['id', 'project', 'project_name', 'version', 'version_name', 'original_content',
                  'analysis_result', 'modules_count', 'requirements_count', 'created_at', 'updated_at',
                  'analyzed_by', 'document_name', 'document_type']
        read_only_fields = ['id', 'created_at', 'updated_at']

class RequirementAnalysisCreateSerializer(serializers.ModelSerializer):
    """需求分析创建序列化器"""
    class Meta:
        model = RequirementAnalysis
        fields = ['project', 'version', 'original_content', 'analysis_result', 'modules_count',
                  'requirements_count', 'analyzed_by', 'document_name', 'document_type']

class AIGenerationLogSerializer(serializers.ModelSerializer):
    """AI生成日志序列化器"""
    # 添加项目和版本信息
    project_name = serializers.ReadOnlyField(source='project.name')
    version_name = serializers.ReadOnlyField(source='version.version_number')
    # 添加生成的用例列表
    generated_cases = serializers.SerializerMethodField()
    
    class Meta:
        model = AIGenerationLog
        fields = ['id', 'project', 'project_name', 'version', 'version_name', 'prompt',
                  'generated_cases_count', 'is_success', 'error_message', 'created_at', 'updated_at',
                  'created_by', 'ai_model', 'generation_time', 'generated_cases']
        read_only_fields = ['id', 'created_at', 'updated_at']
    
    def get_generated_cases(self, obj):
        """获取生成的用例列表"""
        from cases.serializers import TestCaseListSerializer
        # 获取该生成日志关联的所有用例
        case_mappings = GeneratedTestCaseMapping.objects.filter(generation_log=obj)
        test_cases = [mapping.test_case for mapping in case_mappings]
        return TestCaseListSerializer(test_cases, many=True).data

class AIGenerationLogCreateSerializer(serializers.ModelSerializer):
    """AI生成日志创建序列化器"""
    class Meta:
        model = AIGenerationLog
        fields = ['project', 'version', 'prompt', 'generated_cases', 'is_success',
                  'error_message', 'created_by', 'ai_model', 'generation_time']

class GeneratedTestCaseMappingSerializer(serializers.ModelSerializer):
    """生成用例映射序列化器"""
    # 添加用例信息
    test_case_info = serializers.SerializerMethodField()
    # 添加生成日志信息
    generation_log_info = serializers.SerializerMethodField()
    
    class Meta:
        model = GeneratedTestCaseMapping
        fields = ['id', 'generation_log', 'generation_log_info', 'test_case', 'test_case_info', 'is_approved']
        read_only_fields = ['id']
    
    def get_test_case_info(self, obj):
        """获取用例信息"""
        from cases.serializers import TestCaseListSerializer
        return TestCaseListSerializer(obj.test_case).data
    
    def get_generation_log_info(self, obj):
        """获取生成日志信息"""
        return {
            'id': obj.generation_log.id,
            'project_name': obj.generation_log.project.name,
            'version_name': obj.generation_log.version.version_number,
            'created_at': obj.generation_log.created_at
        }

class FileUploadSerializer(serializers.Serializer):
    """文件上传序列化器"""
    file = serializers.FileField()
    project = serializers.PrimaryKeyRelatedField(queryset=Project.objects.all())
    version = serializers.PrimaryKeyRelatedField(queryset=Version.objects.all(), required=False, allow_null=True)
    # 添加API配置相关字段
    api_key = serializers.CharField(required=False, default='')
    api_base = serializers.CharField(required=False, default='')
    model_type = serializers.CharField(required=False, default='deepseek-r1')

class GenerateTestCaseSerializer(serializers.Serializer):
    """生成测试用例序列化器"""
    project = serializers.PrimaryKeyRelatedField(queryset=Project.objects.all())
    version = serializers.PrimaryKeyRelatedField(queryset=Version.objects.all())
    prompt = serializers.CharField(required=False, allow_blank=True)
    template_id = serializers.IntegerField(required=False, allow_null=True)
    requirement_analysis_id = serializers.IntegerField(required=False, allow_null=True)

class GenerateMindmapSerializer(serializers.Serializer):
    """生成思维导图序列化器"""
    project = serializers.PrimaryKeyRelatedField(queryset=Project.objects.all())
    version = serializers.PrimaryKeyRelatedField(queryset=Version.objects.all())
    content = serializers.CharField(required=True, help_text="用于生成思维导图的需求分析内容")